﻿#include <QGuiApplication>
#include <QQmlApplicationEngine>

//#define _TEST_WEBVIEW_
#ifdef _TEST_WEBVIEW_
#include <QtQml/QQmlContext>
#include <QtWebView/QtWebView>
#include <QtNetwork/QUdpSocket>
#include <QtNetwork/QHostInfo>
#endif
#include <QtWebView/QtWebView>

#include "ServerListModel.h"



int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    // 注册C++类型
    qmlRegisterType<ServerListModel>("com.mycompany.customType", 1, 0, "ServerListModel");

    // 初始化webview
    QtWebView::initialize();

    QQmlApplicationEngine engine;

#ifdef _TEST_WEBVIEW_
    QQmlContext *context = engine.rootContext();
    // 设置变量initialUrl
    context->setContextProperty(QStringLiteral("initialUrl"), "");
#endif


    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

#ifdef _TEST_WEBVIEW_
    QUdpSocket udpServerSocket;
    QTimer timer;
    QUdpSocket::connect(&udpServerSocket, &QUdpSocket::readyRead, [&]() {

        QByteArray datagram;
        while (udpServerSocket.hasPendingDatagrams())
        {
            QHostAddress peerAddress;
            quint16 peerPort = 0;
            QString peerName;

            /*
                QString localDomainName = QHostInfo::localDomainName();
                QString localHostName = QHostInfo::localHostName();
                qDebug() << "localDomainName:" << localDomainName
                         << ", localHostName:" << localHostName
                            ;
                */

            datagram.resize(int(udpServerSocket.pendingDatagramSize()));
            udpServerSocket.readDatagram(datagram.data(), datagram.size(), &peerAddress, &peerPort);
            /*
                qDebug() << "peerName:" << peerName
                         << ", peerAddress:" << peerAddress
                         << ", peerPort:" << peerPort
                         << " ### " << "Received datagram: " << datagram.constData();
                */
            static QString lastAddr;
            QString newAddr = QString::fromUtf8(datagram);
            if(newAddr.indexOf("http://") == 0)
            {
                if(newAddr != lastAddr)
                {
                    lastAddr = newAddr;
                    // 设置变量initialUrl
                    //context->setContextProperty(QStringLiteral("initialUrl"), lastAddr);
                    qDebug() << "set initialUrl:" << lastAddr;

                    //timer.stop();

                    QList<QObject*> rootObjects = engine.rootObjects();
                    if(!rootObjects.empty())
                    {
                        QObject* rootObject = rootObjects.at(0);
                        qDebug() << "rootObject:" << rootObject;
                        // 查找list模型
                        QObject* objModel = rootObject->findChild<QObject*>("serverListModel");
                        qDebug() << "serverListModel:" << objModel;
                        if(objModel)
                        {
                            ServerListModel *model = qobject_cast<ServerListModel*>(objModel);
                            model->addServer("exoskeleton", lastAddr);
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }

            /*QHostInfo::lookupHost(peerAddress.toString(), [](QHostInfo info) {
                    qDebug() << "lookupHost::peerName:" << info.hostName()
                                << ", peerAddress:" << info.addresses()
                                ;
                });*/

        }
    } );

    QTimer::connect(&timer, &QTimer::timeout, [&](){
        // 发送广播
        QByteArray datagram = "helloWebServer";
        udpServerSocket.writeDatagram(datagram, QHostAddress::Broadcast, 45454);
    });
    //timer.start(2000);
#endif


    return app.exec();
}
